package org.onvivals.module.system.controller;

import org.onvivals.common.param.PageParam;
import org.onvivals.common.web.Result;
import org.onvivals.module.system.entity.SysMenu;
import org.onvivals.module.system.param.SysMenuParam;
import org.onvivals.module.system.service.ISysMenuService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Tag(name = "菜单管理")
@RestController
@RequestMapping("/system/menu")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SysMenuController {

    private final ISysMenuService menuService;

    @Operation(summary = "查询全部菜单")
    @GetMapping()
    public Result<List<SysMenu>> list(SysMenuParam param) {
        PageParam<SysMenu, SysMenuParam> page = new PageParam<>(param);
        page.setDefaultOrder("sort_number");
        List<SysMenu> menuList = menuService.list(page.getOrderWrapper());
        return Result.OK(menuList);
    }

    @Operation(summary ="根据id查询菜单")
    @GetMapping("/{id}")
    public Result<SysMenu> get(@PathVariable("id") Long id) {
        return Result.OK(menuService.getById(id));
    }

    @Operation(summary ="添加菜单")
    @PostMapping()
    public Result<?> add(@RequestBody SysMenu menu) {
        if (menu.getParentId() == null) {
            menu.setParentId(0L);
        }
        if (menuService.save(menu)) {
            return Result.OK("添加成功");
        }
        return Result.error("添加失败");
    }

    @Operation(summary ="修改菜单")
    @PutMapping()
    public Result<?> update(@RequestBody SysMenu menu) {
        if (menuService.updateById(menu)) {
            return Result.OK("修改成功");
        }
        return Result.error("修改失败");
    }

    @Operation(summary ="删除菜单")
    @DeleteMapping("/{id}")
    public Result<?> remove(@PathVariable("id") Long id) {
        if (menuService.removeById(id)) {
            return Result.OK("删除成功");
        }
        return Result.error("删除失败");
    }



}
